package com.marcjmcd.cop4331;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONObject;

public class Directions 
{
	
	String origin = "";
	String destination = "";
	LinkedList<String> output = new LinkedList<String>();
	Framework obj=new Framework();
	
	public Directions(String origin,String destination) 
	{
		this.origin = origin;
		this.destination = destination;
	}
	
	public LinkedList<String> calculate() throws IOException, Exception
	{
		BufferedReader BR = new BufferedReader(new InputStreamReader(obj.gsearch("http://maps.googleapis.com/maps/api/directions/json?origin="+origin+"&destination="+destination+"&sensor=false")));
		StringBuilder SB = new StringBuilder();
		String line1 = null;
		
		while ((line1 = BR.readLine()) != null)
			SB.append(line1 + "\n");
		
		BR.close();
		String line=SB.toString();
		
		//System.out.println(line);
		
		JSONObject json = new JSONObject(line);
		JSONArray gson=json.getJSONArray("routes");
		JSONObject kson=gson.getJSONObject(0);
		JSONArray lson=kson.getJSONArray("legs");
		JSONObject ason=lson.getJSONObject(0);
		JSONArray bson=ason.getJSONArray("steps");
		
		for(int i=0;i<bson.length();i++)
		{
			JSONObject cson=bson.getJSONObject(i);
			String s=cson.getString("html_instructions");
			
			int k=0;
			
			for(int j=0;j<s.length();j++)
			{	
				if(s.charAt(j)=='<')k=j;
				{
					if(s.charAt(j)=='>')
					{
						s=s.substring(0, k)+" "+s.substring(j+1);
						j=-1;
					}
				}
			}
		
			//TTS output = new TTS(s);
			
			
	
			for(int l=0;l<1000;l++){}
			
			//System.out.println((i+1)+".) "+s);
			//output.start(s);
			
			output.add(s);
		}
		
		//Returns a string array that contains the directions
		return output;
	}
}
